<template>
  <!-- 入库单表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="700"
      draggable
      @close="closeDialog"
      class="srmstoreedit"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
      >
        <el-row>
          <!-- <el-col :span="24">
            <el-form-item label="二维码编号" prop="outCode">
              <el-input
                style="width: 520px"
                v-if="!props.isReadonly"
                v-model="formData.outCode"
                placeholder="请输入二维码编号"
                clearable
                @change="outCodeChange"
              />
              <span v-else>{{ formData.stockBatch }}</span>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="物料" prop="materialId">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.materialCode"
                placeholder="请选择物料号"
                clearable
                readonly
                @click="showWorkOrderSelect"
              >
                <template #append>
                  <el-button type="success" plain @click="showWorkOrderSelect"
                    >选择</el-button
                  >
                </template>
              </el-input>
              <span v-else>{{ formData.materialName }}</span>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="入库类型" prop="inboundTypeId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.inboundTypeId"
                clearable
                placeholder="请选择入库类型"
                @change="inboundChange"
              >
                <el-option
                  v-for="item in inboundTypes"
                  :key="item.id"
                  :label="item.inboundTypeName"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ formData.inboundTypeName }}</span>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="供应商" prop="partnerId">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.partnerCode"
                placeholder="请选择供应商"
                clearable
              >
                <template #append>
                  <el-button type="success" plain @click="showWorkOrderSelect2"
                    >选择</el-button
                  >
                </template>
              </el-input>
              <span v-else>{{ formData.partnerName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存储批次" prop="stockBatch">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.stockBatch"
                placeholder="请输入存储批次"
                clearable
              />
              <span v-else>{{ formData.stockBatch }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="流水号" prop="serial">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.serial"
                placeholder="请输入流水号"
                clearable
              />
              <span v-else>{{ formData.serial }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="POSA" prop="poSa">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.poSa"
                placeholder="请输入POSA"
                clearable
              />
              <span v-else>{{ formData.poSa }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行号" prop="sd">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.sd"
                placeholder="请输入行号"
                clearable
              />
              <span v-else>{{ formData.sd }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select
                v-model="formData.warehouseId"
                clearable
                placeholder="请选择仓库"
                @change="warehouseChange"
                @clear="warehouseClear"
              >
                <el-option
                  v-for="item in warehouses"
                  :key="item.id"
                  :label="item.warehouseCode + '-' + item.warehouseName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="存储区" prop="storageSectionId">
              <el-select
                v-model="formData.storageSectionId"
                clearable
                :disabled="props.isReadonly ? true : false"
                placeholder="请选择存储区"
                @change="storageSectionChange"
                @clear="storageSectionClear"
              >
                <el-option
                  v-for="item in storageSections"
                  :key="item.id"
                  :label="item.storageSectionName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="料架" prop="shelfId">
              <el-select
                v-model="formData.shelfId"
                clearable
                :disabled="props.isReadonly ? true : false"
                placeholder="请选择料架"
                @change="shelfChange"
                @clear="shelfClear"
              >
                <el-option
                  v-for="item in shelfs"
                  :key="item.id"
                  :label="item.shelfName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓位" prop="binId">
              <el-select
                v-model="formData.binId"
                clearable
                :disabled="props.isReadonly ? true : false"
                placeholder="请选择仓位"
                @change="binChange"
                @clear="binClear"
              >
                <el-option
                  v-for="item in bins"
                  :key="item.id"
                  :label="item.binName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可用数量" prop="quantity">
              <el-input-number
                v-model="formData.quantity"
                placeholder="请输入可用数量"
                :min="0"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="RFID" prop="rfId">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.rfId"
                placeholder="请输入RFID"
                clearable
              />
              <span v-else>{{ formData.rfId }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
      <wms-conten-select
        :visible="selectDialogSELECT.visible"
        @change-visible="changeVisibleSELECT"
        :brekList="brekList"
      />
      <wms-partner-select
        :visible="selectDialogSELECT2.visible"
        @change-visible="changeVisibleSELECT2"
        :brekList="brekList2"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "wmsSRMSTOREADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

//工作任务选择弹窗显隐
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    console.log("选择的数据", data);
    formData.materialId = data.id;
    formData.materialName = data.materialName;
    formData.materialCode = data.materialCode;
  }
};

const brekList = ref([]);
const showWorkOrderSelect = () => {
  console.log("showWorkOrderSelect");
  selectDialogSELECT.value.visible = true;
  // if (formData.mesWorkOrderPlanId != "") {
  //   brekList.value.push(formData);
  // }
};

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  orderNo: "",
  inboundTypeId: "",
  inboundTypeCode: "",
  inboundTypeName: "",
  storeTime: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  supplyBatch: "",
  stockBatch: YYMMDD(),
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  warehouseId: "",
  warehouseCode: "",
  warehouseName: "",
  storageSectionId: "",
  storageSectionCode: "",
  storageSectionName: "",
  shelfId: "",
  shelfCode: "",
  shelfName: "",
  binId: "",
  binCode: "",
  binName: "",
  quantity: "",
  quantityUnit: "",
  outCode: "",
  extenalCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  poSa: "",
  sd: "",
  serial: "",
});

/** rules规则 */
const rules = reactive({
  materialId: [{ required: true, message: "请填写物料", trigger: "blur" }],
  inboundTypeId: [
    { required: true, message: "请填选择入库类型", trigger: "blur" },
  ],
  stockBatch: [{ required: true, message: "请填写存储批次", trigger: "blur" }],
  serial: [{ required: true, message: "请填写流水号", trigger: "blur" }],
  partnerId: [{ required: true, message: "请选择供应商", trigger: "blur" }],
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "blur" }],
  binId: [{ required: true, message: "请选择仓位", trigger: "blur" }],
  quantity: [{ required: true, message: "请填写可用数量", trigger: "blur" }],
});

const isValidated = ref(false);

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.orderNo = "";
  formData.inboundTypeId = "";
  formData.inboundTypeCode = "";
  formData.inboundTypeName = "";
  formData.storeTime = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.supplyBatch = "";
  formData.stockBatch = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

function YYMMDD() {
  var myDate = new Date();
  var month = myDate.getMonth() + 1;
  var Day = myDate.getDate();
  var today = "";
  if (month < 10) {
    if (Day < 10) {
      today =
        myDate.getFullYear().toString().slice(-2) + "0" + month + "0" + Day;
    } else {
      today = myDate.getFullYear().toString().slice(-2) + "0" + month + Day;
    }
  } else {
    if (Day < 10) {
      today = myDate.getFullYear().toString().slice(-2) + month + "0" + Day;
    } else {
      today = myDate.getFullYear().toString().slice(-2) + month + Day + "";
    }
  }
  return today;
}

const loading = ref(false);

/** 入库单保存提交 */
async function handleSubmit() {
  if (formData.stockBatch.length != 6) {
    ElMessage.error("批次必须为6位");
    return;
  }
  if (formData.serial.length != 6) {
    ElMessage.error("流水号必须为6位");
    return;
  }

  formData.outCode = `${formData.materialCode}${formData.stockBatch}${formData.serial}${formData.partnerCode}Q${formData.quantity}`;

  if (formData.poSa) {
    formData.outCode += `SA${formData.poSa}`;
  }
  if (formData.sd) {
    formData.outCode += `SD${formData.sd}`;
  }
  const resData = await request({
    url: `/wms/srmasn/barcodeParsing/${formData.outCode}`,
    method: "get",
  }).finally(() => {});

  if (resData.code == 200) {
    formRef.value.validate(async (valid: any) => {
      if (valid) {
        loading.value = true;
        const text = formData.id ? "编辑" : "新增";
        console.log("formData", toRaw(formData));
        await request({
          url: "/wms/srmstore/save",
          method: "post",
          data: formData,
        }).finally(() => {
          loading.value = false;
        });
        ElMessage.success(text + `成功`);
        closeDialog();
        emit("reset-table", formData.id);
        isValidated.value = false;
      } else {
        isValidated.value = true;
      }
    });
  }
}

async function getdetails() {
  let sondetails = await request({
    url: "/wms/srmstore/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

onMounted(() => {
  getWarehouses();
  //getInboundType();
  getPartner();
});

async function outCodeChange() {
  const data = await request({
    url: "/wms/srmasn/barcodeParsing/" + formData.outCode,
    method: "get",
  });
  console.log(data.data);
  formData.materialId = data.data.materialId;
  formData.materialCode = data.data.materialCode;
  formData.materialName = data.data.materialName;
  formData.poSa = data.data.poSa;
  formData.sd = data.data.sd;
  formData.serial = data.data.serial;
  formData.stockBatch = data.data.batch;
  formData.partnerId = data.data.partnerId;
  formData.partnerCode = data.data.partnerCode;
  formData.partnerName = data.data.partnerName;
  formData.quantity = data.data.quantity;
  formData.quantityUnit = data.data.unitName;
}

let partners = ref([]);
async function getPartner() {
  const data = await request({
    url: "/wms/mdmpartner/getList",
    method: "get",
  });
  partners.value = data.data;
}

function partnerChange() {
  var partner = partners.value.find((item) => {
    return item.id === formData.partnerId;
  });
  formData.partnerCode = partner.partnerCode;
  formData.partnerName = partner.partnerName;
}

// let inboundTypes = ref([]);
// async function getInboundType() {
//   const data = await request({
//     url: "/wms/wmsinboundtype/getList",
//     method: "post",
//     data: {},
//   });
//   inboundTypes.value = data.data;
// }

function inboundChange() {
  var inbound = inboundTypes.value.find((item) => {
    return item.id === formData.inboundTypeId;
  });
  formData.inboundTypeCode = inbound.inboundTypeCode;
  formData.inboundTypeName = inbound.inboundTypeName;
}
let warehouses = ref([]);
let shelfs = ref([]);
let bins = ref([]);
let storageSections = ref([]);

async function getWarehouses() {
  const data = await request({
    url: "/wms/wmswarehouse/getList",
    method: "get",
    params: { organizationId: formData.organizationId },
  });
  warehouses.value = data.data;
}

function warehouseChange(id: string) {
  if (id) {
    var warehouse = warehouses.value.find((item) => {
      return item.id === formData.warehouseId;
    });
    formData.warehouseCode = warehouse.warehouseCode;
    formData.warehouseName = warehouse.warehouseName;
    getStorageSections();
    getShelf();
    getbin();
  }
}

function storageSectionChange(id: string) {
  if (id) {
    var storageSection = storageSections.value.find((item) => {
      return item.id === formData.storageSectionId;
    });
    formData.storageSectionCode = storageSection.storageSectionCode;
    formData.storageSectionName = storageSection.storageSectionName;
    getShelf();
    getbin();
  }
}
async function getbin() {
  formData.binId = "";
  formData.binCode = "";
  formData.binName = "";
  const data = await request({
    url: "/wms/wmsbin/getOptionList",
    method: "post",
    data: {
      shelfId: formData.shelfId,
      storageSectionId: formData.storageSectionId,
      warehouseId: formData.warehouseId,
      deleted: 0,
    },
  });
  bins.value = data.data;
}
function shelfChange(id: string) {
  if (id) {
    var shelf = shelfs.value.find((item) => {
      return item.id === formData.shelfId;
    });
    formData.shelfCode = shelf.shelfCode;
    formData.shelfName = shelf.shelfName;
    getbin();
  }
}

function binChange(id: string) {
  if (id) {
    var bin = bins.value.find((item) => {
      return item.id === formData.binId;
    });
    formData.binCode = bin.binCode;
    formData.binName = bin.binName;
  }
}
async function getStorageSections() {
  formData.storageSectionId = "";
  formData.storageSectionCode = "";
  formData.storageSectionName = "";
  const data = await request({
    url: "/wms/wmsstoragesection/getOptionList",
    method: "post",
    data: {
      warehouseId: formData.warehouseId,
    },
  });
  storageSections.value = data.data;
}

function warehouseClear() {
  getWarehouses();
  getStorageSections();
  getShelf();
  getbin();
}

function storageSectionClear() {
  getStorageSections();
  getShelf();
  getbin();
}

function shelfClear() {
  getShelf();
  getbin();
}
function binClear() {
  formData.binId = "";
  formData.binCode = "";
  formData.binName = "";
}
async function getShelf() {
  formData.shelfId = "";
  formData.shelfCode = "";
  formData.shelfName = "";
  const data = await request({
    url: "/wms/wmsshelf/getOptionList",
    method: "post",
    data: {
      storageSectionId: formData.storageSectionId,
      warehouseId: formData.warehouseId,
    },
  });
  shelfs.value = data.data;
}

//工作任务选择弹窗显隐
const selectDialogSELECT2 = ref({
  visible: false,
});
const changeVisibleSELECT2 = (val: boolean, data: any) => {
  selectDialogSELECT2.value.visible = val;
  if (data) {
    console.log("选择的数据", data);
    formData.partnerId = data.partnerId;
    formData.partnerName = data.partnerName;
    formData.partnerCode = data.partnerCode;
  }
};

const brekList2 = ref([]);
const showWorkOrderSelect2 = () => {
  console.log("showWorkOrderSelect");
  selectDialogSELECT2.value.visible = true;
  // if (formData.mesWorkOrderPlanId != "") {
  //   brekList2.value.push(formData);
  // }
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
//:deep(.search-container .el-input.el-input--default.el-input--suffix) {
// 固定宽度
//width: 190px !important;
//}
//:deep(.search-container .el-form-item--default .el-form-item__label) {
// 固定宽度
//justify-content: end;
//}
</style>
